<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\ResourceBk;
use App\Models\ResourceBusinessName;
use App\Models\ResourceCdbt;
use App\Models\ResourceCollect;
use App\Models\ResourceCxzx;
use App\Models\ResourceLeer;
use App\Models\ResourceQqrd;
use App\Models\ResourceTotal;
use App\Models\ResourceTotalAccessNum;
use App\Models\ResourceTotalType;
use App\Models\ResourceType;
use App\Models\ResourceXyts;
use App\Models\ResourceYrd;
use App\Models\ResourceYtys;
use App\Models\ResourceZwzx;
use App\Models\ResourceZy;
use App\Validate\ResourceTotalValidate;
use Illuminate\Support\Facades\Log;

/**
 * 数字资源(对接外部资源)
 */
class ResourceTotalController extends Controller
{
    public $model = null;
    public $typeModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ResourceTotal();
        $this->typeModel = new ResourceType();
        $this->validate = new ResourceTotalValidate();
    }


    /**
     * 资源类型 (系统大类)
     */
    public function typeList()
    {
        $condition[] = ['is_del', '=', 1];
        return $this->typeModel->getFilterList(['id', 'img', 'img_click', 'type_name'], $condition, 'sort ASC');
    }

    /**
     * 根据自定义类型获取资源列表
     * @param custom_type_id  自定义资源类型id  未传表示全部
     * @param keywords 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getCustomTypeResourceLists()
    {
        $custom_type_id = $this->request->custom_type_id;
        $keywords = $this->request->keywords;
        $limit = $this->request->input('limit', 10);


        $resourceTotalTypeModel = new ResourceTotalType();
        $res = $resourceTotalTypeModel->getCustomTypeResourceLists($keywords, $custom_type_id, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 根据资源类型获取资源列表 （最新上架也可用此接口）
     * @param resource_business_id 资源商id
     * @param big_type_id  资源类型id  未传表示全部  （大类）
     * @param type_id  资源类型id  未传表示全部 (小类)
     * @param keywords 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function lists()
    {
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $type_id = $this->request->type_id;
        $keywords = $this->request->keywords;
        $limit = $this->request->input('limit', 10);

        $res = $this->model->lists($keywords, $resource_business_id, $big_type_id, $type_id, null, null, null, null, null, null, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['browse_num'] = !empty($val['browse_num']) ? format_number($val['browse_num']) : null; //位数转换
            $res['data'][$key]['big_type_name'] = !empty($val['con_big_type']) ? $val['con_big_type']['type_name'] : '';
            unset($res['data'][$key]['con_big_type']);
        }

        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 获取资源详情
     * @param guid  资源guid (可能是加密后的密文)
     * @param resource_business_id  资源商id  改为可选
     */
    public function detail()
    {
        //增加验证场景进行验证
        // if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
        //     return $this->returnApi(201,  $this->validate->getError());
        // }
        $guid = $this->request->guid;
        $user_id = $this->request->user_info['id'];
        $resource_id = null;
        if (strlen($guid) != 32) {
            //Log::error('解析小程序id:' . $guid);
            $resource_id = decrypt1($guid, config('other.resource_encrypt_key'));
            if (!$resource_id) {
                return $this->returnApi(201, '参数错误');
            }
            $resource_business_id = ResourceTotal::where('id', $resource_id)->value('resource_business_id'); //只能从总表取数据
        } else {
            $resource_business_id = $this->request->resource_business_id;
            if (empty($resource_business_id)) {
                $resource_business_id = ResourceTotal::where('guid', $this->request->guid)->value('resource_business_id');
            }
        }

        $res = $this->model->detail(null, $resource_id, $this->request->guid);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        //添加浏览量
        $browse_num = mt_rand(1, 5); //随机数量
        $this->model->addBrowseNum($resource_business_id, $res->guid, $browse_num);
        //添加阅读记录
        if ($user_id) {
            $resourceTotalAccessNumModel = new ResourceTotalAccessNum();
            $resourceTotalAccessNumModel->addAllAccessNum($res['guid'], $res['resource_business_id'], $res['big_type_id'], $user_id, 2, date('Y-m-d'), $browse_num);
        }

        $data = $res->toArray();
        $data['browse_num'] = !empty($data['browse_num']) ? format_number($data['browse_num']) : 0; //位数转换
        $data['type_name'] = !empty($data['con_type']) ? $data['con_type']['type_name'] : '';
        $data['big_type_name'] = !empty($data['con_big_type']) ? $data['con_big_type']['type_name'] : '';
        //获取资源商名称
        $data['resource_business_name'] = ResourceBusinessName::where('id', $data['resource_business_id'])->where('is_del', 1)->value('name');

        unset($data['con_type']);
        unset($data['con_big_type']);
        if ($user_id) {
            //判断是否收藏
            $is_collect = ResourceCollect::isCollect($this->request->guid, $user_id);
            $data['is_collect'] = $is_collect ? true : false;
        } else {
            $data['is_collect'] = false; //未登录，默认未收藏
        }

        //以后可以删除，无意义
        if (!empty($data['bid'])) {
            $data['bid'] = trim($data['bid']);
        }

        //获取推荐资源
        $limit_number = $data['big_type_id'] == 3 ? 8 : 9; //视频推荐8个，其余9个
        $recom_resource = $this->model->getRecomResourceLists($data['big_type_id'], $data['type_id'], $limit_number);
        foreach ($recom_resource as $key => $val) {
            $recom_resource[$key]['big_type_name'] = !empty($val['con_big_type']) ? $val['con_big_type']['type_name'] : '';
            unset($recom_resource[$key]['con_big_type']);
        }
        $data['recom_resource'] = $recom_resource;

        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 资源收藏与取消收藏
     * @param token  用户token  用户筛选用户是否收藏
     * @param guid  资源guid
     */
    public function collectAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_collect_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $model = new ResourceCollect();
        list($res, $msg) = $model->collectAndCancel($this->request->guid, $user_id);
        if ($res) {
            return $this->returnApi(200, $msg . "成功", true);
        }
        return $this->returnApi(202, $msg . "失败");
    }

    /**
     * 我的资源收藏类型列表
     * @param token  用户token  用户筛选用户是否收藏
     */
    public function myCollectTypeList()
    {
        $user_id = $this->request->user_info['id'];
        $resourceCollectModel = new ResourceCollect();
        $res = $resourceCollectModel->collectTypeList($user_id);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 我的资源收藏列表
     * @param token  用户token  用户筛选用户是否收藏
     * @param big_type_id  资源大类型id  未传表示全部
     * @param keywords 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function myCollectList()
    {
        $limit = $this->request->input('limit', 10);
        $user_id = $this->request->user_info['id'];
        $big_type_id = $this->request->big_type_id;

        $resourceCollectModel = new ResourceCollect();
        $res = $resourceCollectModel->collectList($user_id, null, $big_type_id, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 批量删除收藏书架的书籍
     * @param collect_id 收藏id 多个逗号拼接
     * @param token  用户token  用户筛选用户是否收藏
     */
    public function batchDelCollectBook()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_batch_del_collect_book')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $collect_id = $this->request->collect_id;

        $resourceCollectModel = new ResourceCollect();
        $res = $resourceCollectModel->batchDelCollectBook($collect_id, $user_id);
        if ($res) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, "删除失败");
    }



    /**
     * 获取新语听书图书目录(云图有声目录、掌阅目录、中文在线目录)
     * @param guid  资源guid
     * @param resource_business_id  资源商id
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceBookCatalogue()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_get_book_catalogue')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $page = $this->request->page ?? 1;
        $limit = $this->request->limit ?? 10;

        switch ($this->request->resource_business_id) {
            case 1:
                $model = new ResourceZwzx();
                $res = $model->getBookCatalogue($this->request->guid);
                break;
            case 3:
                $model = new ResourceYtys(); //云图有声
                $res = $model->getBookCatalogue($this->request->guid, $page, $limit);
                break;
            case 6:
                $model = new ResourceXyts(); //新语听书
                $res = $model->getBookCatalogue($this->request->guid);
                break;
            case 8:
                $model = new ResourceZy(); //掌阅
                $res = $model->getBookCatalogue($this->request->guid);
                break;
            case 9:
                $model = new ResourceYrd(); //元阅读
                $res = $model->getBookCatalogue($this->request->guid);
                break;
            case 999:
                $model = new ResourceCdbt();
                $res = $model->getBookCatalogue($this->request->guid);
                break;
            default:
                return $this->returnApi(203, '暂无数据');
                break;
        }
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 获取资源阅读界面地址
     * @param token 用户token
     * @param guid  资源guid
     * @param chapter_id  章节id   可为空   resource_business_id 为 3 ,8 可选
     * @param resource_business_id  资源商id
     * @param href  toc 目录中的href (resource_business_id 9 元阅读可选)
     * @param fragment_id  toc 目录中的fragmentId （锚点）(resource_business_id 9 元阅读可选)
     */
    public function getResourceBookSkipAddress()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_get_book_skip_address')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        // if (in_array($this->request->resource_business_id, [3, 8]) && empty($this->request->chapter_id)) {
        //     return $this->returnApi(201, '章节id不能为空');
        // }
        // if (in_array($this->request->resource_business_id, [9]) && empty($this->request->href)) {
        //     return $this->returnApi(201, '章节参数有误');
        // }

        switch ($this->request->resource_business_id) {
            case 1:
                $model = new ResourceZwzx();
                $res = $model->getZwzxSingleSign($this->request->token, $this->request->guid);
                break;
            case 2:
                $model = new ResourceQqrd();
                $res = $model->getResourceSkipAddress($this->request->guid);
                break;
            case 3:
                $model = new ResourceYtys();
                $res = $model->getYtysChapterAudioAddress($this->request->chapter_id);
                break;
            case 4:
                $model = new ResourceBk();
                $res = $model->getBkSingleSign($this->request->token, $this->request->guid);
                break;
            case 5:
                $model = new ResourceLeer(); //乐儿资源，不请求这个接口
                $res = $model->getResourceSkipAddress($this->request->guid);
                break;
            case 6:
                $model = new ResourceXyts();
                $res = $model->getXytsChapterAudioSkipAddress($this->request->guid);
                break;
            case 7:
                $model = new ResourceCxzx();
                $res = $model->getResourceSkipAddress($this->request->token, $this->request->guid);
                break;
            case 8:
                $model = new ResourceZy();
                $res = $model->getZyChapterAddress($this->request->token, $this->request->guid, $this->request->chapter_id);
                break;
            case 9:
                $model = new ResourceYrd(); //音频在章节已经返回了，不调用这个接口
                $res = $model->getChapterAddress($this->request->token, $this->request->guid, $this->request->chapter_id, $this->request->href, $this->request->fragment_id);
                break;
            case 999:
                $model = new ResourceCdbt();
                $res = $model->getCdbtEbookSkipAddress($this->request->guid);
                break;
            default:
                return $this->returnApi(203, '暂无数据');
                break;
        }
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
